<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Controller for user login/logout functionality in the template engine.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMTEUserController extends DMAbstractController {

	private function authenticate($alias) {
		try {
			$as = DMAuthenticationServiceFactory::getService();
			$rep = $this->getHTTPRequest()->getRepresentation();
			$user = new DMUser($rep->getFormValue("username"));
			$result = $as->authenticate($user, $rep->getFormValue("password"));
			if ($result) {
				$this->getSession()->setUser($user);
				$dest_params = "objects";
				if ($rep->getFormValue("destination_params")) {
					$dest_params = $rep->getFormValue("destination_params");
				}
				DMHTTPRequest::redirectToParams($dest_params);
				die;
			} else {
				// mitigate brute-force attacks
				sleep(DMAbstractController::AUTHENTICATION_DELAY);
				header("HTTP/1.1 401 Unauthorized");
				$this->getSession()->setFlash(new DMFlash(
						DMLocalizedString::getString("LOGIN_FAILED"), false));
			}
		} catch (DMException $e) {
			$this->getSession()->setFlash(
					new DMFlash($e->getMessage(), false));
		}

		$this->loginPage($alias);
	}

	public function index($alias) {
		if (!$alias) {
			$alias = "/dmdefault";
		}
		$alias = DMCollection::getSanitizedAlias($alias);
		if ($this->getHTTPRequest()->getMethod() == DMHTTPMethod::POST) {
			$this->authenticate($alias);
		} else {
			$this->loginPage($alias);
		}
	}

	private function loginPage($alias) {
		$col = null;
		if ($alias != "/dmdefault") {
			$col = DMCollectionFactory::getCollection($alias);
		}
		$path = "/templates/user/login.html.php";
		$tpl = $this->getTemplateSet()->getTemplateAtPathname($path);
		global $view;
		$view = new DMLoginView($tpl, $this->getSession(),
				$col);
	}

	/**
	 * If the user is logged in, logs out the user. Otherwise redirects to the
	 * login page.
	 *
	 * @since 0.1
	 */
	public function logout($alias) {
		$alias = DMCollection::getSanitizedAlias($alias);

		$user = $this->getSession()->getUser();
		if ($user) {
			$this->getSession()->setFlash(new DMFlash(
					DMLocalizedString::getString("LOGOUT_SUCCESS"), false));
			$as = DMAuthenticationServiceFactory::getService();
			$as->logout($user);
		}

		$params = $alias ? "objects" . $alias : "objects";
		DMHTTPRequest::redirectToParams($params);
		die;
	}

}

